
$(function () {

    // console.log(flowInstId);
    // console.log(flowInstTaskId);

    if ($.isEmptyObject(flowInstTaskId)) {
        //流程发起人查看 审批记录 时，不显示“审批”tab
        $('a[href="#approve"]').parent().remove();
    }

    //获取流程图数据
    getFlowView();

    //监听选择文件事件
    $('#fileupload').change(function () {
        let files = $(this).prop('files');
        for (let i = 0; i < files.length; i++) {
            let file = files[i];
            let fileName = file.name;
            if (fileName.indexOf(".") === -1) {
                toastr.warning('禁止上传没有扩展名的附件');
                continue;
            }
            let $previewItem = $(  '<div class="preview-item">' +
                '<span class="pull-left">'+ file.name +'</span>' +
                '<a class="pull-right" href="javascript:void(0);">删除</a>\n' +
                '</div>');
            $previewItem.data('file', file);
            $previewItem.find('a').click(function () {
                $(this).parent().remove();
            });
            $('.preview').append($previewItem);
        }
    });

    //提交审批
    $('#submit').click(function () {
        //验证是否签名
        if (signaturePad.isEmpty()) {
            toastr.warning('请签字');
            //阻止默认事件
            return false;
        }

        //再次确认
        let passText = $('#approve select[name="pass"]').find("option:selected").text();
        let passVal = $('#approve select[name="pass"]').find("option:selected").val();
        let inst = $('#approve textarea[name="inst"]').val();
        btConfirm('您的审批结果是“'+ passText +'”，审批后无法撤回，请再次确认。', function () {
            //获取签名数据
            const dataURL = signaturePad.toDataURL();
            let flowInstTaskAppEntity = {
                "flowInstId": flowInstId,
                "flowInstTaskId": flowInstTaskId,
                "pass": passVal,
                "inst": inst,
                "signImg": dataURL
            };

            $.ajax({
                type: "POST",
                url: "/flowInstTask/approveTask",
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(flowInstTaskAppEntity),
                success: function (data) {
                    if (data.code === SUCCESS_CODE) {
                        //toastr.success(data.msg);
                        //上传附件
                        uploadFile(data.payload, data.msg)
                    } else {
                        toastr.error(data.msg);
                    }
                }
            });
        });

        //阻止默认事件
        return false;
    });
})

/**
 * 上传文件
 */
function uploadFile(flowInstTaskAppEntity, msg) {
    //获取文件对象
    let fileList = [];
    $('.preview-item').each(function (index, e) {
        let file = $(this).data('file');
        fileList.push(file);
    });

    if (fileList.length > 0) {
        //有附件
        //初始化
        $('#fileupload').fileupload();
        $('#fileupload').fileupload('send',
            {
                files: fileList,
                url: '/attach/upload',
                sequentialUploads: true,
                formData: {
                    flowInstId: flowInstTaskAppEntity.flowInstId,
                    flowInstTaskId: flowInstTaskAppEntity.flowInstTaskId,
                    flowInstTaskAppId: flowInstTaskAppEntity.id
                }
            })
            .success(function (data, textStatus, jqXHR) {
                // console.log(data)
                // console.log(textStatus)
                // console.log(jqXHR)
                if (data.code === SUCCESS_CODE) {
                    //成功
                    toastr.success(msg);
                    //跳转到待办列表
                    setTimeout(function () {
                        goto("/admin/flowinsttask/approve_task_list.html");
                    }, 2000);
                } else {
                    toastr.error(msg + ';' + data.msg);
                }
            })
            .error(function (jqXHR, textStatus, errorThrown) {
                //遇到错误
                toastr.error(msg + ';上传附件失败');
            })
            .complete(function (result, textStatus, jqXHR) {
                //完成，相当于finally
                //console.log('complete');
            });
        //销毁
        $('#fileupload').fileupload('destroy');
    } else {
        //没有附件
        toastr.success(msg);
        // 跳转到“我的申请”列表
        setTimeout(function () {
            goto("/admin/flowinsttask/approve_task_list.html");
        }, 2000);
    }

}

/**
 * 获取流程图数据
 */
function getFlowView() {
    $.ajax({
        type: "GET",
        url: "/flowInst/getById",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: {"id": flowInstId},
        success: function (data) {
            if (data.code === SUCCESS_CODE) {
                //console.log(data);

                let flowInstVo = data.payload;
                let flowInstEntity = flowInstVo.flowInstEntity;

                $('#flowStartUserName').text(flowInstEntity.startUserName);
                $('#flowInstName').text(flowInstEntity.name);
                $('#flowSn').text(flowInstEntity.sn);

                let startTaskFlowAttachEntityList = flowInstVo.startTaskFlowAttachEntityList;
                for (var i = 0; i < startTaskFlowAttachEntityList.length; i++) {
                    let startTaskFlowAttachEntity = startTaskFlowAttachEntityList[i];
                    let $startTaskFlowAttachEntity = $('<a href="javascript:void(0);">'+ startTaskFlowAttachEntity.name + '.' + startTaskFlowAttachEntity.ext +'</a>');
                    $startTaskFlowAttachEntity.click(function () {
                        //下载文件
                        download(startTaskFlowAttachEntity.id);
                    });
                    $('.start-attach').append($startTaskFlowAttachEntity);
                }

                let complete = true;
                let flowInstTaskEntityList = flowInstVo.flowInstTaskEntityList;
                $.each(flowInstTaskEntityList, function () {
                    let flowInstTaskEntity = this;
                    let taskType = flowInstTaskEntity.type;
                    if (taskType === 'start' || taskType === 'end') {
                        return true;//相当于continue，return false 相当于break
                    }

                    let taskNode = $('#taskTemplate [taskType="' + taskType + '"]');
                    let taskNodeClone = taskNode.clone(false);
                    taskNodeClone.find('[name="name"]').text(flowInstTaskEntity.name);
                    taskNodeClone.find('[name="des"]').text(flowInstTaskEntity.des);
                    taskNodeClone.find('[name="assignees"]').text(flowInstTaskEntity.assigneesName);
                    //给节点按钮赋予节点id，改变节点样式
                    taskNodeClone.find('div.btn').attr('id', flowInstTaskEntity.id);
                    if (flowInstTaskEntity.id === flowInstEntity.currTaskId && flowInstTaskEntity.type !== 'end') {
                        taskNodeClone.find('div.btn').removeClass('btn-primary');
                        taskNodeClone.find('div.btn').addClass('btn-danger');
                    }

                    if (flowInstTaskEntity.pass !== 1) {
                        complete = false;
                    }

                    //将完成的步骤的箭头变成绿色
                    if (complete) {
                        taskNodeClone.find('div.line-arrow').addClass('line-arrow-comp');
                    }

                    //审批记录
                    let flowInstTaskAppEntityList = flowInstTaskEntity.flowInstTaskAppEntityList;
                    if (!$.isEmptyObject(flowInstTaskAppEntityList)) {
                        //箭头线的高度
                        let lineArrowHeight = 133;

                        for (let i = 0; i < flowInstTaskAppEntityList.length; i++) {
                            lineArrowHeight = lineArrowHeight + 38;
                            let flowInstTaskAppEntity = flowInstTaskAppEntityList[i];
                            let attach = '';
                            for (let j = 0; j < flowInstTaskAppEntity.flowAttachEntityList.length; j++) {
                                let flowAttachEntity = flowInstTaskAppEntity.flowAttachEntityList[j];
                                attach = attach + '<a href="javascript:void(0);" attchId="'+ flowAttachEntity.id +'">'+ flowAttachEntity.name + '.' + flowAttachEntity.ext +'</a>';
                            }
                            let $appRecord = $('<tr>' +
                                '<td>'+ flowInstTaskAppEntity.assigneeName +'</td>' +
                                '<td>'+ (flowInstTaskAppEntity.pass===1 ? '通过' : '拒绝') +'</td>' +
                                '<td>'+ flowInstTaskAppEntity.inst +'</td>' +
                                '<td class="signImg"><a href="javascript:void(0);" ' +
                                '       data-toggle="popover" data-html="true" data-placement="top" data-trigger="click"' +
                                '       data-template=" <div class=\'popover\' role=\'tooltip\' style=\'max-width:440px; margin-bottom:20px\'>' +
                                '           <div class=\'arrow\'></div>' +
                                '           <h3 class=\'popover-title\'></h3>' +
                                '           <div class=\'popover-content\'>' +
                                '           </div>' +
                                '           </div>"' +
                                '       data-original-title="<img style=\'width:280px\' src=\''+ flowInstTaskAppEntity.signImg +'\'/>"><img src="'+ flowInstTaskAppEntity.signImg +'"/></a></td>' +
                                '<td>'+ flowInstTaskAppEntity.startTime +'</td>' +
                                '<td>'+ flowInstTaskAppEntity.endTime +'</td>' +
                                '<td class="attach">'+ attach +'</td>' +
                                '</tr>');
                            $appRecord.find('.attach a').click(function () {
                                //下载附件
                                download($(this).attr('attchId'));
                            });
                            taskNodeClone.find('tbody').append($appRecord);
                        }

                        //设置箭头线的高度
                        taskNodeClone.find('div.line-arrow').css('height', lineArrowHeight+'px');
                    } else {
                        taskNodeClone.find('[name="approveRecord"]').parent().remove();
                    }

                    $('.flow [taskType="end"]').before(taskNodeClone);
                });

                $('[data-toggle="popover"]').popover();

            } else {
                toastr.error(data.msg);
            }
        }
    });
}

/**
 * 下载附件
 * @param id
 */
function download(id) {
    window.open('/attach/download?id=' + id,'下载附件')
}